﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DAO
{
    public class LoginDao
    {
        SqlHelper sqlHelper = null;
        public static string fullName = null;
        public static int userID = 1;
        public static bool adminFlag = false;
        public LoginDao()
        {
            sqlHelper = new SqlHelper();
        }

        public bool checkConnect()
        {
            return SqlHelper.CheckConnection();
        }

        public bool login(string userName, string pass)
        {
            DataTable table = SqlHelper.ExecuteDataTable("LOGIN", CommandType.StoredProcedure,
               "@USR_NAME", userName);
            if (table != null && table.Rows.Count > 0)
            {
                DataRow row = table.Rows[0];
                if (row["PASS"] != null && row["PASS"].ToString() == Encrypt.EncryptionToString(pass))
                {
                    fullName = row["FULL_NAME"] == null ? "" : row["FULL_NAME"].ToString();
                    userID = row["ID"] == null ? 0 : int.Parse(row["ID"].ToString());
                    if (row["AD_FLG"] != null && "T".Equals(row["AD_FLG"].ToString().ToUpper()))
                    {
                        adminFlag = true;
                    }
                    else
                    {
                        adminFlag = false;
                    }
                    return true;
                }

            }
            return false;
        }

        public int changePassword(string userName, string currentPass, string pass, string fullName)
        {
            DataTable table = SqlHelper.ExecuteDataTable("LOGIN", CommandType.StoredProcedure,
               "@USR_NAME", userName);
            if (table != null && table.Rows.Count > 0)
            {
                DataRow row = table.Rows[0];
                if (row["PASS"] != null && row["PASS"].ToString() == Encrypt.EncryptionToString(currentPass))
                {
                    if (SqlHelper.ExecuteNonQuery("SP_UPDATE_PASS", CommandType.StoredProcedure,
                    "@USER_NAME", userName,
                    "@PASS", Encrypt.EncryptionToString(pass),
                    "@FULL_NAME", fullName))
                    {
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return -1;
                }
            }
            return 0;
        }
    }
}
